package controllers;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import job.MajorJob;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aton.db.Config;

import play.Play;
import play.cache.Cache;
import play.libs.Codec;
import services.CaseService;
import services.LogService;
import services.SystemParamService;
import services.WordService;
import utils.BizConstants;
import utils.DocToHtml;
import utils.HttpUtils;
import utils.ShellUtil;
import vos.ResultVo;
import vos.ReturnCode;
import models.DrCase;
import models.DrCaseTemp;
import models.DrKeywords;
import models.DrVKeywords;
import models.SystemOperator;

/**
 * 关键词优化
 * @author wangshaoming
 *
 */
public class KeyWordController extends BaseController {
	public static final Logger shelllog=LoggerFactory.getLogger("shell");
	/**
	 * 跳转到关键词优化页面
	 */
	public static void keyword(String courtid,String caseid){
		//验证权限
		SystemOperator oper=getLoginUser();
		if(BizConstants.SERVICE_ROLE.equals(oper.getRoleId())){
			render("errors/404.html");
		}
		if(StringUtils.isEmpty(courtid)||StringUtils.isEmpty(caseid)){
			render("LiveConfigController/liveConfig.html");
		}
		//获取历史优化内容
		List<DrVKeywords> words=WordService.listWord();
		for(DrVKeywords word :words){
			if(StringUtils.isNotEmpty(word.getCourtname())){
				word.nameString=word.modifyString+" "+word.getCourtname();
			}else{
				word.nameString=word.modifyString;
			}
		}
		if(words!=null&&words.size()>0){
			renderArgs.put("firstKey", words.get(0).getWordid());
		}
		renderArgs.put("courtid", courtid);
		renderArgs.put("caseid", caseid);
		renderArgs.put("words", words);
		render();
	}
	/**
	 * 保存优化记录
	 * @param content
	 * @param wordid
	 */
	public static void saveKeyWord(String content,String courtid){
		if(StringUtils.isEmpty(content)){
			renderRespondJson(ReturnCode.ErrorCode, "请输入要优化的内容");
		}
		if(content.length()>2000){
			renderRespondJson(ReturnCode.ErrorCode, "优化内容长度不可大于2000");
		}
		if(StringUtils.isEmpty(courtid)){
			renderRespondJson(ReturnCode.ErrorCode, "请先进行直播配置");
		}
		//拼装最新的优化内容
		DrKeywords keyword=new DrKeywords();
		keyword.setContent(content);
		keyword.setIsuse(new BigDecimal(1));
		keyword.setCourtid(courtid);
		keyword.setWordid(Codec.UUID());
		keyword.setModifytime(new Date());
		keyword.setCreatetime(new Date());
		keyword.setCreatename(getLoginUser().getOperatorid());
		String Ip=request.remoteAddress;
		boolean issave=WordService.saveKeyWords(keyword,getLoginUser(),Ip);
		if(issave){
			renderRespondJson(ReturnCode.SuccessCode,"保存成功");
		}
		renderRespondJson(ReturnCode.ErrorCode, "保存失败");
	}
	/**
	 * 删除优化记录
	 */
	public static void deleteKeyWord(String wordid){
		if(StringUtils.isEmpty(wordid)){
			renderRespondJson(ReturnCode.ErrorCode, "请选择要删除的优化记录");
		}
		DrKeywords word=WordService.getById(wordid);
		if(word==null){
			renderRespondJson(ReturnCode.ErrorCode, "删除的记录不存在");
		}
		String ip=request.remoteAddress;
		boolean isdel=WordService.deleteKeyWord(wordid,getLoginUser(),ip);
		if(isdel){
			renderRespondJson(ReturnCode.SuccessCode,"删除成功");
		}
		renderRespondJson(ReturnCode.SuccessCode,"删除失败");
	}
	/**
	 * 清空优化效果
	 */
	public static void clearKeyWord(){
		String ip=request.remoteAddress;
		
		Integer status=(Integer)Cache.get(BizConstants.MAJORKEYWORDS_STATUS);
		if(status!=null&&status!=1){
			renderRespondJson(ReturnCode.ErrorCode, "正在进行优化请稍候执行");
		}
		//获取活跃案件（休庭和开庭）
		List<DrCase> cases=CaseService.getLivingCase();
		if(cases!=null&&cases.size()>0){
			renderRespondJson(ReturnCode.ErrorCode, "有案件正在执行中，不允许进行优化");
		}
		ResultVo vo=major("");
		if(vo.code!=null){
			renderJSON(vo);
		}
		//启动轮询状态任务
		new MajorJob().now();
		//保存日志
		LogService.saveLog(getLoginUser().getOperatorid(), ip, "清空优化效果", "清空优化效果", new Date());
		renderRespondJson(ReturnCode.SuccessCode, "清空成功");
	}
	/**
	 * 进行优化
	 * @param content
	 * @param wordid
	 */
	public static void majorKeyWord(String content){
		if(StringUtils.isEmpty(content)){
			renderRespondJson(ReturnCode.ErrorCode, "优化内容不可为空");
		}
		String ip=request.remoteAddress;
		Integer status=(Integer)Cache.get(BizConstants.MAJORKEYWORDS_STATUS);
		if(status!=null&&status!=1){
			renderRespondJson(ReturnCode.ErrorCode, "正在进行优化请稍候执行");
		}
		//获取活跃案件（休庭和开庭）
		List<DrCase> cases=CaseService.getLivingCase();
		if(cases!=null&&cases.size()>0){
			renderRespondJson(ReturnCode.ErrorCode, "有案件正在执行中，不允许进行优化");
		}
		ResultVo vo=major(content);
		if(vo.code!=null){
			renderJSON(vo);
		}
		//启动轮询状态任务
		new MajorJob().now();
		//记录操作日志
		LogService.saveLog(getLoginUser().getOperatorid(), ip, "优化关键字", "优化", new Date());
		renderRespondJson(ReturnCode.SuccessCode, "优化成功");
	}
	/**
	 * 获取缓存状态
	 */
	public static void getMajorStatus(){
		Integer key=(Integer)Cache.get(BizConstants.MAJORKEYWORDS_STATUS);
		ResultVo vo=new ResultVo(ReturnCode.SuccessCode,"获取成功",key);
		if(key==1){
			Cache.safeDelete(BizConstants.MAJORKEYWORDS_STATUS);
		}
		renderJSON(vo);
	}
	/**
	 * 点击下一步
	 * @param caseid
	 */
	public static void majorNext(String caseid){
		if(StringUtils.isEmpty(caseid)){
			renderRespondJson(ReturnCode.ErrorCode, "案件为空");
		}
		DrCaseTemp cases=CaseService.getTempById(caseid);
		if(cases==null){
			renderRespondJson(ReturnCode.ErrorCode, "案件不存在");
		}
		renderRespondJson(ReturnCode.SuccessCode, "更新成功");
	}
	/**
	 * 执行关键词优化
	 * @param content 优化内容，清空效果时为空
	 * @return
	 */
	public static ResultVo major(String content){
		ResultVo vo=new ResultVo();
		String majorFile=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("SSH_MAJOR_FILE"));
		if(StringUtils.isEmpty(majorFile)){
			vo=new ResultVo(ReturnCode.ErrorCode, "系统参数关键词文本存放位置未设置");
			return vo;
		}
		//创建临时文件
		try {
			File file=new File(majorFile);
			if(!file.exists()){
				file.createNewFile();
			}
			FileOutputStream writer=new FileOutputStream(majorFile);
			writer.write(content.getBytes("UTF-8"));
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			vo=new ResultVo(ReturnCode.ErrorCode, "初始化文件失败");
			return vo;
		}
		String majorShell=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("SSH_MAJOR_SHELL"));
		String majorip=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("SSH_RESTART_ASR_IP"));
		String majoruser=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("SSH_RESTART_ASR_USER"));
		String majorpass=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("SSH_RESTART_ASR_PASS"));
		//调用接口
		//Map<String,Object> shellMap=ShellUtil.exec("sh "+majorShell+"create_model.sh");
		
		String shellTxt="cd "+majorShell+"&& ./create_model.sh";
		shelllog.info("执行关键词优化脚本命令为"+shellTxt);
		Map<String,Object> shellMap=ShellUtil.execAndPass(majorip,majoruser,majorpass,shellTxt);
		if(shellMap==null){
			vo=new ResultVo(ReturnCode.ErrorCode, "执行优化脚本失败");
			return vo;
		}
		int shellStatus=(int)shellMap.get("status");
		if(shellStatus!=0){
			shelllog.info("执行关键词优化脚本失败,错误输出为"+(String)shellMap.get("outErr"));
			shelllog.info("执行关键词优化脚本失败,日志输出为"+(String)shellMap.get("outPut"));
			vo=new ResultVo(ReturnCode.ErrorCode, "执行优化脚本失败");
			return vo;
		}
		Cache.set(BizConstants.MAJORKEYWORDS_STATUS, 0);
		return vo;
	}
	/**
	 * 导入word
	 * @param word
	 */
	public static void importFile(File fileToUpload){
		response.contentType="text/html;charset=utf-8";
		if(fileToUpload==null){
			renderRespondJson(ReturnCode.ErrorCode,"请选择文件");
		}
		String fileName=fileToUpload.getName();
		if(!fileName.endsWith(".doc")&&!fileName.endsWith(".docx")){
			renderRespondJson(ReturnCode.ErrorCode,"文件格式不正确");
		}
		String htmlfile=Play.applicationPath+"/public/importTmp/";
		File filedir=new File(htmlfile);
		if(!filedir.exists()){
			filedir.mkdir();
		}
	    htmlfile+=Codec.UUID()+".html";
	    String html=DocToHtml.toHtmlString(fileToUpload,htmlfile);
	    File file =new File(htmlfile);
	    if(file.exists()){
	    	file.delete();
	    }
	    ResultVo vo=new ResultVo(ReturnCode.SuccessCode,"获取成功",html);
		renderJSON(vo);
	}
	/**
	 * 获取第一条信息
	 * @param wordid 信息id
	 */
	public static void getFirstContent(String wordid){
		if(StringUtils.isEmpty(wordid)){
			ResultVo vo=new ResultVo(ReturnCode.SuccessCode,"未选中记录","");
			renderJSON(vo);
		}
		String content=WordService.getContentBywordid(wordid);
		ResultVo vo=new ResultVo(ReturnCode.SuccessCode,"未选中记录",content);
		renderJSON(vo);
	}
}
